﻿using System;
using System.ServiceManager.Facade;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.UI.WpfWizardFramework;

namespace ServiceManager.TFSIntegration
{
    public class TFSAdminWizardData : WizardData
    {
        private const string managementPackID = "F30960D3-7C16-A0BE-DFB6-6DD8117ACE9D";
        private const string className = "ServiceManager.TFSIntegration.TFSSettings";

        public string TFSUrl { get; set; }

        public string PortalIncidentUrl { get; set; }

        public Guid Id { get; set; }

        public int SyncFrequency { get; set; }

        public string ResolvedString { get; set; }
        
        internal TFSAdminWizardData(EnterpriseManagementObject emo)
        {
            var classAdminSetting = GetAdminSettingClass();

            TFSUrl = emo[classAdminSetting, "TFSUrl"].ToString();
            PortalIncidentUrl = emo[classAdminSetting, "PortalIncidentURL"].ToString();
            int sync;
            if (int.TryParse(emo[classAdminSetting, "SyncFrequency"].Value.ToString(), out sync))
                SyncFrequency = sync;
            ResolvedString = emo[classAdminSetting, "ResolvedString"].ToString();
            Id = emo.Id;
        }

        private static ManagementPackClass GetAdminSettingClass()
        {
            var mp = SCSMServer.GetManagementPack(new Guid(managementPackID));

            return mp.GetClass(className);
        }

        public override void AcceptChanges(WizardMode wizardMode)
        {
            var classAdminSetting = GetAdminSettingClass();

            var adminSettingOject = SCSMServer.GetObject<EnterpriseManagementObject>(Id);

            adminSettingOject[classAdminSetting, "TFSUrl"].Value = TFSUrl;
            adminSettingOject[classAdminSetting, "PortalIncidentURL"].Value = PortalIncidentUrl;
            adminSettingOject[classAdminSetting, "SyncFrequency"].Value = SyncFrequency;
            adminSettingOject[classAdminSetting, "ResolvedString"].Value = ResolvedString;

            adminSettingOject.Commit();

            WizardResult = WizardResult.Success;
        }
    }
}